﻿using Furion.DependencyInjection;
using Newtonsoft.Json;
using OnWork.DataCenter.BLL.Base;
using OnWork.DataCenter.BLL.Base.Dto;
using OnWork.DataCenter.BLL.Standard;
using OnWork.DataCenter.DAL.DataCenter;
using OnWork.DataCenter.Utils.Caches;
using SqlSugar;

namespace OnWork.DataCenter.BLL.DataCenter
{
    /// <summary>
    /// 定时任务配置
    /// </summary>
    public class DSTaskBLL : BaseBLL<DSTask>, ITransient
    {
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SQLReturn> AddDataAsync(DSTask input)
        {
            if (string.IsNullOrEmpty(input.Name))
            {
                return SQLReturn.AddError($"错误:名称不能为空!");
            }

            input.Name = input.Name.Trim();

            bool isExit = await base.Queryable().Where(x => x.Name == input.Name).AnyAsync();
            if (isExit)
            {
                return SQLReturn.AddError($"错误:名称:{input.Name}已存在!");
            }

            var rows = await base.AddAsync(input); //添加
            return SQLReturn.AddSuccess();
        }

        /// <summary>
        /// 复制数据 重新命名
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public async Task<SQLReturn> CopyDataAsync(List<DSTask> items)
        {
            //复制时将名称周增加随机字符
            var Name = DateTime.Now.ToString("fff");
            foreach (var item in items)
            {
                item.Name = item.Name.Trim()+ Name;
                item.Enable = false;
            }
            var rows = await base.AddAsync(items); //添加
            return SQLReturn.AddSuccess();
        }


        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<SQLReturn> DeleteDataAsync(long[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                return SQLReturn.DelError($"错误:删除Id不存在!");
            }
            var rows = await base.DeleteAsync<DSTask>(ids);
            MemoryCacheUtil.Removes(CacheKeys.BLLDataStandard); //清理缓存
            return SQLReturn.DelSuccess(rows);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SQLReturn> UpdateDataAsync(DSTask input)
        {
            if (string.IsNullOrEmpty(input.Name))
            {
                return SQLReturn.UpdateError($"错误:配置名称不能为空!");
            }
            var old = await base.SingleByIdAsync(input.ID);
            input.Name = input.Name.Trim();
            if (!string.IsNullOrEmpty(input.Name))
            {
                if (Queryable().Where(x => x.Name == input.Name && x.Name != old.Name).Any())
                {
                    return SQLReturn.UpdateError($"错误:数据连接名称:{input.Name}已存在!");
                }
            }
            var rows = await base.UpdateAsync(input);
            MemoryCacheUtil.Removes(CacheKeys.BLLDataStandard); //清理缓存
            return SQLReturn.UpdateSuccess(rows);
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SQLReturn> UpdateDataAsync(List<DSTask> input)
        {
            var rows = await base.UpdateAsync(input);
            MemoryCacheUtil.Removes(CacheKeys.BLLDataStandard); //清理缓存
            return SQLReturn.UpdateSuccess(rows);
        }


        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public async Task<SQLReturn<List<DSTask>>> QueryPagedListAsync(BaseQueryPageInput option)
        {
            var querysql = option.ToQuerySQL<DSTask>();

            RefAsync<int> total = 0;
            var query = await Queryable<DSTask>()
                .WhereIF(!string.IsNullOrEmpty(querysql.Where), querysql.Where)
                .OrderByDescending(x=>x.CreateTime)
                .OrderByIF(!string.IsNullOrEmpty(querysql.Order), $"{querysql.Order}")
                .ToPageListAsync(option.PageIndex, option.PageItems, total);
            return SQLReturn<DSTask>.QueryListSuccess(query, total.Value);
        }

        /// <summary>
        /// 返回流程类型的定时任务
        /// </summary>
        /// <returns></returns>
        public async Task<List<DSTask>> GetProcessTypeListAsync()
        {
            return await Queryable().Where(x => x.Enable == true && x.Type == DSTaskType.Process).ToListAsync();
        }

        /// <summary>
        /// 返回流程类型的定时任务
        /// </summary>
        /// <returns></returns>
        public async Task<List<DataStandardTreeDto>> GetStandardsTreeByIdAsync(long id)
        {
            //使用内存缓存
            string _timeCacheKey = CacheKeys.BLLDataStandard + "/GetStandardsTreeByIdAsync/" + id.ToString();
            var result = await MemoryCacheUtil.GetOrCreateAsync(_timeCacheKey, async entry =>
            {
                var ds = await QueryableCopy().Where(x => x.ID == id).FirstAsync();
                if (ds != null)
                {
                    if (!string.IsNullOrEmpty(ds.TaskConfigView))
                    {
                        var dto = JsonConvert.DeserializeObject<List<DataStandardTreeDto>>(ds.TaskConfigView);
                        return dto;
                    }
                }
                return null;
            });

            return result;
        }

        /// <summary>
        /// 返回定时任务名称
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetStandardsNameByIdAsync(long id)
        {
            //使用内存缓存
            string _timeCacheKey = CacheKeys.BLLDataStandard + "/GetStandardsNameByIdAsync/" + id.ToString();
            var result = await MemoryCacheUtil.GetOrCreateAsync(_timeCacheKey, async entry =>
            {
                var ds = await QueryableCopy().Where(x => x.ID == id).FirstAsync();
                if (ds != null)
                {
                    return ds.Name;
                }
                return null;
            });

            return result;
        }

    }
}